package com.imooc.service.impl;

import com.imooc.es.pojo.Items;
import com.imooc.service.ItemsESService;
import com.imooc.utils.PagedGridResult;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

/**
 * @description: 商品接口实现
 * @author: Yz
 * @create: 2020-09-09 14:32
 **/
@Service
public class ItemsESServiceImpl implements ItemsESService {

    @Autowired
    private ElasticsearchTemplate esTemplate;

    /**
     * 查询商品
     * @param keywords
     * @param sort
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page,pageSize);
        SortBuilder sortBuilder = null;
        if (sort.equals("c")) {
            sortBuilder = new FieldSortBuilder("sellCounts")
                    .order(SortOrder.DESC);
        } else if (sort.equals("p")) {
            sortBuilder = new FieldSortBuilder("price")
                    .order(SortOrder.ASC);
        } else {
            sortBuilder = new FieldSortBuilder("itemName.keyword")
                    .order(SortOrder.ASC);
        }
        String itemFieldName = "itemName";
        SearchQuery searchQuery = new NativeSearchQueryBuilder().
                withQuery(QueryBuilders.matchQuery(itemFieldName,keywords)).
                withPageable(pageable).
                withSort(sortBuilder).
                build();
        AggregatedPage<Items> itemsList = esTemplate.queryForPage(searchQuery, Items.class);
        System.out.println("检索后的总分页数目为："+itemsList.getTotalPages());
        PagedGridResult gridResult = new PagedGridResult();
        gridResult.setRows(itemsList.getContent());
        gridResult.setPage(page+1);
        gridResult.setTotal(itemsList.getTotalPages());
        gridResult.setRecords(itemsList.getTotalElements());
        return gridResult;
    }
}
